import Cookies from "js-cookie";

export default defineNuxtRouteMiddleware((to, from) => {
    const login = to.meta.login;
    const userStore = useUserStore();

    if (process.server) {
        const headers = useRequestHeaders(["cookie"]);
        const cookies = headers["cookie"] ? headers["cookie"].split(";") : [];
        for (let cookie of cookies) {
            if (cookie.includes("ykj_token")) {
                userStore.token = cookie.split("=")[1];
                break;
            }
        }
    }

    if (process.client) {
        userStore.token = Cookies.get("ykj_token");
    }

    if (login && !userStore.isLogin && to.path !== "/login.html") {
        return navigateTo("/login.html?redirect=" + from.fullPath);
    }
});
